<template>
    <div class="content">
      <div class="content-head">
        <el-form :inline="true" :model="formData" label-position="left">
          <el-form-item label="选择月份" label-width="70px" class="form-item">
            <el-date-picker v-model="formData.date" type="month" size="mini" value-format="yyyy-MM-dd" :editable="false"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="reset_btn">重置</el-button>
            <el-button type="success" size="mini" icon="el-icon-search" @click="search_btn">查询</el-button>
            <el-button v-if="false" type="info" size="mini" icon="el-icon-download" :loading="exportBtnLoading" @click="export_btn">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content-table">
        <div class="table-date">
          <span class="date-tip">{{ formatDate(formData.date,6) + '成本汇总表'}}</span>
        </div>
        <div class="table-main">
          <!-- :show-summary="true" :summary-method="getSummaries" -->
          <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" highlight-current-row :max-height="tableMaxHeight" class="content-table-item">
            <el-table-column prop="productCode" label="物料编号" align="center" width="100"></el-table-column>
            <el-table-column prop="productName" label="物料名称" align="center" width="80"></el-table-column>
            <el-table-column prop="workerCount" label="理论工数" align="center" width=""></el-table-column>
            <el-table-column prop="actualWorkerCount" label="实际工数" align="center" width=""></el-table-column>
            <el-table-column prop="sumTheoreticalWorkingHours" label="理论工时" align="center" width=""></el-table-column>
            <el-table-column prop="sumActualWorkingHours" label="实际工时" align="center" width=""></el-table-column>
            <el-table-column prop="sumTargetOutput" label="理论产出" align="center" width=""></el-table-column>
            <el-table-column prop="sumActualOutput" label="实际产出" align="center" width=""></el-table-column>
            <el-table-column prop="sumActualOutput" label="理论人工成本" align="center" width="110"></el-table-column>
            <el-table-column prop="actualLaborCost" label="实际人工成本" align="center" width="110"></el-table-column>
            <el-table-column prop="costPerUnit" label="理论单件成本" align="center" width="110"></el-table-column>
            <el-table-column prop="actualCostPerUnit" label="实际单件成本" align="center" width="110"></el-table-column>
            <el-table-column prop="sumTheoreticalDepreciation" label="理论总折旧" align="center" width="100"></el-table-column>
            <el-table-column prop="theoreticalDepreciationUnit" label="单件理论折旧" align="center" width="110"></el-table-column>
            <el-table-column prop="sumActualDepreciation" label="实际总折旧" align="center" width="100"></el-table-column>
            <el-table-column prop="actualDepreciationUnit" label="单件实际折旧" align="center" width="110"></el-table-column>
            <el-table-column prop="scrapUnit" label="理论单件报废" align="center" width="110"></el-table-column>
            <el-table-column prop="actualScrapUnit" label="实际单件报废" align="center" width="110"></el-table-column>
            <el-table-column prop="sumScrap" label="理论总报废" align="center" width="100"></el-table-column>
            <el-table-column prop="sumActualScrap" label="实际总报废" align="center" width="100"></el-table-column>
            <el-table-column prop="totalMaterialCost" label="理论料总费用" align="center" width="110"></el-table-column>
            <el-table-column prop="materialCost" label="实际料总费用" align="center" width="110"></el-table-column>
            <el-table-column prop="materialWasteCostPerUnit" label="理论单件料费用" align="center" width="120"></el-table-column>
            <el-table-column prop="actualMaterialWasteCostPerUnit" label="实际单件料费用" align="center" width="120"></el-table-column>
            <el-table-column prop="totalIndirectMaterialsCost" label="理论间接总耗材" align="center" width="120"></el-table-column>
            <el-table-column prop="actualTotalIndirectMaterialsCost" label="实际间接总耗材" align="center" width="120"></el-table-column>
            <el-table-column prop="indirectMaterialsCostPerUnit" label="理论单件耗材" align="center" width="110"></el-table-column>
            <el-table-column prop="actualIndirectMaterialsCostPerUnit" label="实际单件耗材" align="center" width="110"></el-table-column>
            <el-table-column prop="sellingPricePerUnit" label="理论单件售价" align="center" width="110"></el-table-column>
            <el-table-column prop="actualSel" label="实际单件售价" align="center" width="110"></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="content-footer" v-if="false">
        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20,40,80,100,200]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
      </div>
    </div>
  </template>
  
  <script>
  import { reqMonthlyCostList } from "@/api/monthlyCostSummmary.js";
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
import { formatDate } from "@/utils/toosls";
  export default {
    name:"monthlyCostSummary",  //月度成本汇总表
    components:{
      TableHeadFilter
    },
    data() {
      return {
        formData:{
          date:this.formatDate(new Date(),5)
        },
        tableData:[],
        currentPage:1,
        pageSize:100,
        total:0,
        tableLoading:false,
        exportBtnLoading:false,
        tableMaxHeight:450
      }
    },
    mounted(){
      //精致环境下进行自动旋转
      //autoOrientation();
      this.getMonthlyCostList();
      document.title = "月度成本汇总表";
      this.calculateTableMaxHeight();
      window.addEventListener("resize",this.calculateTableMaxHeight);
    },
    beforeDestroy(){
      window.removeEventListener("resize",this.calculateTableMaxHeight);
    },
    methods:{
      //分页获取报工列表信息
      async getMonthlyCostList () {
        this.tableLoading = true;
        const { date } = this.formData;
        const parameter = { monthlyDate:date };
        reqMonthlyCostList(parameter).then(res => {
          if(res.data.code === 200){
            this.tableData = res.data.data;
            this.total = res.data.data.totalElements;
          }
          this.tableLoading = false;
          console.log("分页获取月度成本报表信息",res);
        }).catch(err => {
          console.log('分页获取月度成本报表信息',err);
          this.$message({type:"error",message:"列表数据获取失败"});
          this.tableLoading = false;
        })
      },
      //查询重置导出按钮
      search_btn(){
        const { date } = this.formData;
        if(date === null){
          this.$message({type:"warning",message:"请先选择报月份"});
          return;
        }
        this.currentPage = 1;
        this.pageSize = 10;
        this.getMonthlyCostList();
      },
      reset_btn(){
        this.formData.date = this.formatDate(new Date(),5);
        this.currentPage = 1;
        this.pageSize = 10;
        this.getMonthlyCostList();
      },
      export_btn() {
        const { reportDate, workshop, classes, productCode, workReportType} = this.formData;
        const parameter = {startDate:reportDate[0],endDate:reportDate[1],workShop:workshop,classes,productCode, workReportType};
        if(reportDate.length !== 2){
          this.$message({type:"warning",message:"请选择日期后再进行报表数据下载"});
          return;
        }
        this.$confirm('即将导出当前数据内容(内容将根据相关筛选条件进行过滤', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
          .then(async () => {
              this.exportBtnLoading = true;
              let res = await reqOeeStatementExcel(parameter);
              if (res.status === 200) {
                  let blob = res.data;
                  let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
                  const aLink = document.createElement('a');
                  aLink.href = url;
                  let timestamp = new Date().getTime();
                  aLink.setAttribute('download', reportDate + workshop+'生产汇总报表_' + timestamp);
                  document.body.appendChild(aLink);
                  aLink.click();
                  document.body.removeChild(aLink);
                  this.$message.success('导出成功');
                  this.exportBtnLoading = false;
              } else {
                  this.$message.error('导出失败,请重试');
                  this.exportBtnLoading = false;
              }
            console.log('oee报表导出api',res);
          }).catch((error) => {
            console.log("oee报表导出error:",error);
            this.$message({type: 'info', message: '已取消导出!'});
            this.exportBtnLoading = false;          
          });
      },
      //分页器
      handleCurrentChange(curPage){
        this.currentPage = curPage;
        //重新获取数据
        this.getMonthlyCostList();
      },
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        //重新获取数据
        this.getMonthlyCostList();
      },
      calculateTableMaxHeight(){
        const dom = document.querySelector(".table-main");
        this.$nextTick(() => {
          this.tableMaxHeight = dom.offsetHeight - 10;
        })
      },
      //格式化时间
      formatDate(val,type){
        let date = new Date(val);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        if(type === 0){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 1){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day);
        } else if (type === 2){
            return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 3){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
        } else if (type === 4){
          return year + "年" + this.addZero(month) + "月" + this.addZero(day) + "日";
        } else if (type === 5){
          return year + "-" + this.addZero(month) + "-" + "01";
        } else if (type === 6){
          return year + "年" + this.addZero(month) + "月";
        }
      },
      addZero(val){
        return val > 9 ? val : "0" + val;
      },
      //tableHeadFiler的change事件
      filterChangeEvent(parameter){
        const { state, filterField, selectedValue } = parameter;
        if(state === 'clear'){
          //清空操作
          if(this.formData[filterField] !== ""){
            this.formData[filterField] = "";
            this.search_btn();
          }
        }
        if(state === 'confirm'){
          //确定操作
          this.formData[filterField] = selectedValue;
          if(selectedValue !== ""){
            this.search_btn();
          }
        }
      },
      getSummaries(parameter) {
        const {columns, data} = parameter;
        const calculateList = new Array();
        const array = ["reportTime","workShop","classes","equipmentType","productNumber","productCode","productName","operator","isStandard"];
        const columnFieldName = ["standardManpower","actualManpower"];
        for(let col = 0; col < columns.length; col ++){
          let calculateListValue = null;
          if(!array.includes(columns[col].property) && columns[col].property){
            let columnSign = "";
            const tmp = data.map(v => {
              const str = v[columns[col].property];
              if(!(str === null || str === "" || str === undefined)){
                const strNumber = str.replace(/[^\d.]/g, '');
                //处理列符号
                const tmp = str.match(/[^0-9.]/g);
                tmp && (tmp.includes("%") || tmp.includes("￥") || tmp.includes("h")) ? columnSign = tmp[0] : "";
                return parseFloat(strNumber);
              } else {
                return 0;
              }
            });
            const count = tmp.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            const columnField = columns[col].property;
            if(columnSign.includes('%')){
              calculateListValue = (count / data.length).toFixed(2) + columnSign;
            } else if(columnSign.includes('￥')) {
              calculateListValue = columnSign + count.toFixed(2);
            } else if(columnSign.includes('h')){
              calculateListValue = count.toFixed(1) + columnSign;
            } else {
              calculateListValue = columnFieldName.includes(columnField) ? count.toFixed(3) : count.toFixed(2);
            }
            calculateList.push(calculateListValue);
          } else {
            col === 0 ? calculateList.push("合计") : calculateList.push("");
          }

        }
        return calculateList;
      },
      calculateColor(value1,value2,type){
        //type 1:OEE
        //type 0:单件成本
        const val1 = value1 === null ? 'aaa' : value1;  //目标
        const val2 = value2 === null ? 'aaa' : value2;  //实际
        if(val1 && val2 && type === 0){
          return Number(val2.replace(/[^\d.]/g, '')) > Number(val1.replace(/[^\d.]/g, ''));
        } else if(val1 && val2 && type === 1) {
          return Number(val1.replace(/[^\d.]/g, '')) > Number(val2.replace(/[^\d.]/g, ''));
        } else {
          return false;
        }
      }
    }
  }
  </script>
  
<style lang='scss' scoped>
.content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1%;
  box-sizing: border-box;
  user-select: none;

  .content-head{
    flex: 0.5;
    .form-item{
      margin-right: 2vw;
    }
  }
  .content-table{
    flex: 8;
    margin: 10px 0;
    .table-date{
      width: 100%;
      height: 2%;
      min-height: 15px;
      margin-bottom: 0.5%;
      display: flex;
      justify-content: right;
    }
    .table-main{
      width: 100%;
      height: 98%;
    }
  }
  .content-footer{
    flex: 0.5;
    display: flex;
    justify-content: flex-end;
  }
}
::v-deep .el-table__header th {
  padding: 0; /* 调整上下内边距 */
}
::v-deep .el-table__row {
  margin-bottom: 15px; /* 调整这个值来改变行间距 */
}
::v-deep .el-table .el-table__cell{
  padding: 0;
}
</style>